﻿using PmSoft.Events;
using PmSoft;
using Modules.SMS.EventArgs;
using ManagementApi.TreeParty.SMS;
using Modules.SMS;

namespace ManagementApi.EventModules;

[UseDI(ServiceLifetime.Singleton, typeof(IEventMoudle))]
public class SmsLogEventModule : IEventMoudle
{
    private readonly IEventBus eventBus;

    public SmsLogEventModule(IEventBus eventBus)
    {
        this.eventBus = eventBus;
    }

    public void RegisterEventHandler()
    {
        eventBus.Subscribe<SMSSendEventArgs, SMSSendEventHandler>();
    }
}

/// <summary>
/// 短信发送事件处理类
/// </summary>
[UseDI(ServiceLifetime.Scoped)]
public class SMSSendEventHandler : IEventHandler<SMSSendEventArgs>
{
    private readonly IEnumerable<ISMSService> smsServices;
    private readonly IConfiguration configuration;
    private readonly SmsSendLogService sendLogService;

    public SMSSendEventHandler(IEnumerable<ISMSService> smsServices, IConfiguration configuration, SmsSendLogService sendLogService)
    {
        this.smsServices = smsServices;
        this.configuration = configuration;
        this.sendLogService = sendLogService;
    }

    /// <summary>
    /// 处理短信发送事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="eventArgs"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentNullException"></exception>
    public Task HandleAsync(object sender, SMSSendEventArgs eventArgs)
    {
        var sendLog = sendLogService.GetLog(eventArgs.MsgId);
        if (sendLog == null)
            throw new ArgumentNullException(nameof(sendLog));

        var providerName = configuration.GetValue<string>("SmsProviderName", "Lexin");
        if (string.IsNullOrEmpty(providerName))
            throw new ArgumentNullException("未设置短信供应商");

        var smsService = smsServices.FirstOrDefault(m => m.GetType().Name.Contains(providerName, StringComparison.OrdinalIgnoreCase));
        if (smsService != null)
        {
            smsService.Send(sendLog);
        }
        return Task.CompletedTask;
    }
}